package cn.besbing.server.controllers.actions;


import cn.besbing.client.enums.BaseResponse;
import cn.besbing.client.enums.StatusCode;
import cn.besbing.model.entities.primary.DbFiles;
import cn.besbing.model.entities.primary.DbFilesExample;
import cn.besbing.model.entities.primary.Project;
import cn.besbing.server.service.limsweb.LimsWebActionsService;
import cn.besbing.server.service.primary.CustomerSqlServiceImpl;
import cn.besbing.server.service.primary.DbFilesServiceImpl;
import cn.besbing.server.utils.DataloaderLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
//@Controller
@RequestMapping("LimsWebControllers")
public class LimsWebControllers {

    @Autowired
    private LimsWebActionsService limsWebActionsService;

    @Autowired
    private CustomerSqlServiceImpl customerSqlService;

    @Autowired
    private DbFilesServiceImpl dbFilesService;



    private BaseResponse baseResponse = new BaseResponse(StatusCode.SUCCESS);

    private String rejectPerson = "";

    private DbFiles dbFiles = null;

    private DbFilesExample dbFilesExample = null;




    /**
     * 单据驳回控制器
     * @param param
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping(value = "rejectReportController")
    public BaseResponse rejectReportController(@RequestParam("param") String param) throws UnsupportedEncodingException {
        String taskidAndRejectContentArr[] = param.split(":");
        DataloaderLogger.getDataloaderLogger().info("{}开始校验单据信息:{}......",this.getClass().getName(),param);
        //前台参数传输错误
        if (taskidAndRejectContentArr == null)
            return new BaseResponse(-12,"前台数据传输错误，单据号/驳回原因/单据类型分离后值空");
        //前台校验不通过，单据号和驳回原因无法分离
        if (taskidAndRejectContentArr.length < 3 || "".equals(taskidAndRejectContentArr[0].trim()) || "".equals(taskidAndRejectContentArr[1].trim()))
            return new BaseResponse(-12,"前台校验不通过，单据号/驳回原因/单据类型无法分离");
        DataloaderLogger.getDataloaderLogger().info("{}校验单据信息结束:{}......",this.getClass().getName(),param);
        //开始执行报告驳回动作和驳回原因写入动作
        DataloaderLogger.getDataloaderLogger().info("{}开始业务操作信息:{}......",this.getClass().getName(),param);
        try{
            /**
             * 驳回校验：如果在满意度评价表中已经存在，则不允许再驳回
             */
            List<Map<String, Object>> listTemp = customerSqlService.selectList("select pk_download_info from report_download_info where billno = '" + taskidAndRejectContentArr[0] + "'");
            if (listTemp.size() > 0){
                return new BaseResponse(-14,"报告"+ taskidAndRejectContentArr[0] + "已经被下载过，禁止再次驳回，若有需要，请联系总部检测中心");
            }
            /**
             * 需求变更：公元2021年6月8日下午，应死产品经理、死老王这个二货申请，取消驳回labware和NC的功能
            //驳回报告
            baseResponse = limsWebActionsService.reportRejectToLabwareAndNC(taskidAndRejectContentArr[0],taskidAndRejectContentArr[2]);
            if (baseResponse.getCode() != 200)
                return baseResponse;
             */
            //写入驳回记录
            //rejectPerson = ((Project)baseResponse.getData()).getCreatedBy();
            rejectPerson = taskidAndRejectContentArr[3];
            baseResponse = limsWebActionsService.writeReportRejectRecords(taskidAndRejectContentArr[0],taskidAndRejectContentArr[1],taskidAndRejectContentArr[2],rejectPerson);
            if (baseResponse.getCode() != 200)
                return baseResponse;
        }catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new BaseResponse(-14,"驳回报告时发生异常：" + e.getStackTrace() + " " + e.getMessage() + " " + e.getCause() + ":" + e.getClass().getName());
        }
        DataloaderLogger.getDataloaderLogger().info("{}结束业务操作信息:{}......",this.getClass().getName(),param);
        return baseResponse;
    }

    /**
     * 报告下载按钮
     * @return
     */
    @PostMapping(value = "downloadReportController")
    public BaseResponse ReportDownload(@RequestBody String JSONStr){
        try{
            baseResponse = limsWebActionsService.DowdloadReport(JSONStr);
        }catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new BaseResponse(-14,"下载报告回写时发生异常：" + e.getStackTrace() + " " + e.getMessage() + " " + e.getCause() + ":" + e.getClass().getName());
        }
        return baseResponse;
    }

    /**
     * 将不符合项（被驳回的报告），以邮件方式，发送给下一步执行人
     * @param JSONStr
     * @return
     */
    @PostMapping(value = "sendRejectBillToUserController")
    public BaseResponse sendRejectBillToUserController(@RequestBody String JSONStr){
        baseResponse = limsWebActionsService.rejectRejectToManager(JSONStr);
        return baseResponse;
    }


    /**
     * 不符合项撤消动作
     * @param JSONStr
     * @return
     */
    @PostMapping(value = "RejectCancelController")
    public BaseResponse RejectCancelController(@RequestBody String JSONStr){
        baseResponse = limsWebActionsService.rejectCancelAction(JSONStr);
        return baseResponse;
    }



    /**
     * 不符合项结项动作
     * @param JSONStr
     * @return
     */
    @PostMapping(value = "RejectConfirmController")
    public BaseResponse RejectConfirmController(@RequestBody String JSONStr){
        baseResponse = limsWebActionsService.rejectConfirmAction(JSONStr);
        return baseResponse;
    }



    ByteArrayOutputStream outStream = null;



    /**
     * 不符合项detail保存动作
     * @param JSONStr
     * @return
     */
    @PostMapping(value = "saveRejectDetail")
    public BaseResponse saveRejectDetail(@RequestBody String JSONStr) {
        JSONObject jsonObject = JSONObject.parseObject(JSONStr);
        jsonObject.put("user", SecurityUtils.getSubject().getPrincipal());
        baseResponse = limsWebActionsService.saveRejectDetail(jsonObject.toJSONString());
        return baseResponse;
    }

    /**
     * 不符合项detail提交动作
     * @param JSONStr
     * @return
     */
    @PostMapping(value = "commitRejectDetail")
    public BaseResponse commitRejectDetail(@RequestBody String JSONStr) {
        JSONObject jsonObject = JSONObject.parseObject(JSONStr);
        jsonObject.put("user", SecurityUtils.getSubject().getPrincipal());
        baseResponse = limsWebActionsService.commitRejectDetail(jsonObject.toJSONString());
        return baseResponse;
    }


    /**
     * 不符合项处理结果退回处理人
     * @param JSONStr
     * @return
     */
    @PostMapping(value = "rejectProcessToProcessor")
    public BaseResponse rejectProcessToProcessor(@RequestBody String JSONStr) {
        baseResponse = limsWebActionsService.rejectProcessToProcessor(JSONStr);
        return baseResponse;
    }




    /**
     * 不符合项上传报告控制器
     * @param file
     * @param
     * @return
     */
    //@RequestMapping(value = "/uploadRejectFiles")
    //@ResponseBody
    //public synchronized BaseResponse uploadRejectFiles(MultipartFile file){
        //public synchronized BaseResponse uploadRejectFiles(MultipartFile file, HttpServletRequest request ,HttpServletResponse response){
        //try{
            /*
            InputStream inStream = file.getInputStream();
            response.getOutputStream().close();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();

            //创建一个Buffer字符串 
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕 
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来 
            while ((len = inStream.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度 
                outStream.write(buffer, 0, len);
            }

            byte[] returnVar = outStream.toByteArray();
            //关闭输入流 
            inStream.close();
            //outStream.flush();
            outStream.close();
             */
            //request.getInputStream().close();
            //response.getOutputStream().close();
            //baseResponse = limsWebActionsService.rejectUploadFilesService(file);
        //}catch (Exception e){
            //e.printStackTrace();
        //}
        //baseResponse = limsWebActionsService.rejectUploadFilesService(file);
        //return baseResponse;
    //}


    /**
     * 工具类
     * @param file
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(MultipartFile file) throws Exception {
        InputStream inStream = file.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串 
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕 
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来 
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度 
            outStream.write(buffer, 0, len);
        }
        //关闭输入流 
        inStream.close();
        byte[] returnVar = outStream.toByteArray();
        outStream.flush();
        outStream.close();
        //把outStream里的数据写入内存 
        return returnVar;
    }

}
